/*
 * MQTT_plus.cpp
 *
 *  Created on: Jan 6, 2025
 *      Author: Hai Li
 */

#include "mqtt_plus.h"

extern PubSubClient client;

/// @brief 设置MQTT的Clientid
/// @param myIot 
/// @param clientID 
void setClientId(DFRobot_Iot * myIot, String clientID)
{
   int len = clientID.length();
   printf("len = %d\r\n", len);
   if(len == 0)
   {
      return;
   }
   if(myIot == NULL)
   {
      return;
   }
   printf("clientid = %s\r\n", clientID.c_str());
   // if(myIot->_clientId != NULL)
   // {
   //    free(myIot->_clientId);
   //    myIot->_clientId = NULL;
   // }
   myIot->_clientId = (char *) malloc(len + 1);
   if(!myIot->_clientId)
      return;
   strcpy(myIot->_clientId, clientID.c_str());
   return;
}

/// @brief MQTT 发送保留消息
/// @param myIot DFRobot_Iot实例 
/// @param topic 主题 
/// @param message 消息内容 
/// @param qos QoS 
void sendRetainedMessage(DFRobot_Iot * myIot, String topic, String message, int qos)
{
   if(myIot == NULL)
   {
      return;
   }
    if(!myIot->wifiStatus() || !myIot->connected())
        return;
    client.setPublishQos(qos > 0 ? MQTTQOS1: MQTTQOS0);
    client.publish(topic.c_str(), message.c_str(), 1);
    delay(250);
    return;
}